package com.zcy.example.dao.impl;

import com.zcy.example.dao.SearchDao;
import com.zcy.example.pojo.Item;
import com.zcy.example.pojo.SearchResult;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: zcy
 * @data: 16:57 2017/11/3
 */
@Service
public class SearchDaoImpl implements SearchDao {

    @Resource(name = "client")
    private SolrClient client;

    @Override
    public SearchResult search(SolrQuery query) throws IOException, SolrServerException {
        //返回值对象
        SearchResult result = new SearchResult();
        //根据查询条件查询索引库
        QueryResponse queryResponse = client.query(query);
        //取查询结果
        SolrDocumentList solrDocumentList = queryResponse.getResults();
        //取查询结果总数量
        result.setRecordCount(solrDocumentList.getNumFound());
        //商品列表
        List<Item> itemList = new ArrayList<Item>();
        //取高亮显示
        Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();
        //取商品列表
        for (SolrDocument solrDocument : solrDocumentList) {
            //创建一商品对象
            Item item = new Item();
            item.setId((String) solrDocument.get("id"));
            //取高亮显示的结果
            List<String> list = highlighting.get(solrDocument.get("id")).get("name");
            List<String> keylist = highlighting.get(solrDocument.get("id")).get("keywords");
            String title = "";
            String keywords="";
            if (list != null && list.size()>0) {
                title = list.get(0);
            } else {
                title = solrDocument.get("name").toString();
            }
            if (keylist != null && keylist.size()>0) {
                keywords = list.get(0);
            } else {
                keywords = solrDocument.get("keywords").toString();
            }
            item.setTitle(title);
            item.setName((String) solrDocument.get("name"));
            item.setPrice((Long) solrDocument.get("price"));
            item.setKeywords(keywords);
            item.setCategory((String) solrDocument.get("category"));
            item.setDescription((String) solrDocument.get("description"));
            //添加的商品列表
            itemList.add(item);
        }
        result.setItemList(itemList);
        return result;

    }
}
